package com.yuanluludev.lib_base.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider

/**
 * 带网络的碎片基类
 * yuanLulu
 */
abstract class BaseVMFragment<VM : BaseViewModel> : BaseFragment() {

    protected open lateinit var mViewModel: VM

    private var lazyLoaded = false

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        useDataBinding(true)
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun initViewModel() {
        mViewModel = ViewModelProvider(this).get(viewModelClass())
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        commonObserve()
        observe()

    }

    override fun onResume() {
        super.onResume()
        // 实现懒加载
        if (!lazyLoaded) {
            lazyLoadData()
            lazyLoaded = true
        }
    }

    open fun commonObserve() {
        mViewModel.showLoadingWithTip.observe(viewLifecycleOwner) {
            showLoading(it)
        }
        mViewModel.showLoading.observe(viewLifecycleOwner) {
            if (it) showLoading()
        }
        mViewModel.hideLoading.observe(viewLifecycleOwner) {
            if (it) hideLoading()
        }
        mViewModel.successResultTip.observe(viewLifecycleOwner) {
            onSuccess(it.state, it.tipMessage)
        }
        mViewModel.errorResultTip.observe(viewLifecycleOwner) {
            onError(it.state, it.tipMessage)
        }
    }

    open fun observe() {
        //  override if need
    }

    /**
     * 获取ViewModel的class
     */
    protected abstract fun viewModelClass(): Class<VM>

    /**
     * 请求成功
     */
    open fun onSuccess(successState: Int, successMsg: String) {
        // Override if need
    }

    /**
     * 请求失败
     */
    open fun onError(errorState: Int, errorMsg: String) {
        // Override if need
    }

    /**
     * 懒加载数据
     */
    open fun lazyLoadData() {
        // Override if need
    }

}